package automation;

import java.util.ArrayList;

public class Central {

    private ArrayList<ISensor> sensors;
    private ArrayList<IWindow> windows;
    private boolean opened = false;

    public Central() {
        this.sensors = new ArrayList<ISensor>();
        this.windows = new ArrayList<IWindow>();
    }

    public void addSensor(ISensor sensor) {
        sensor.register(this);
        this.sensors.add(sensor);
        System.out.println(String.format("sensor %d added!", sensors.size()));
    }

    public void addWindow(IWindow window) {
        this.windows.add(window);
        int size = windows.size();
        window.setID(size);
        System.out.println(String.format("window %d added!", size));
    }

    void receive(int value, ISensor sensor) {
        boolean should = sensor.shouldBeOpen(value, this.opened);

        // if windows already have the right status
        if (this.opened == should) {
            return;
        }

        ArrayList<IWindow> failures = new ArrayList<IWindow>();

        for (IWindow window : this.windows) {
            // should windows be open
            if (should) {
                this.opened = true;
                boolean failure = window.open();
                if (failure) {
                    System.out.println(String.format("window with the id %d failed", window.getID()));
                    failures.add(window);
                    //windows.removeIf(w -> w.equals(window));
                }
            } else {
                window.close();
                this.opened = false;
            }
        }

        // remove intersections between failures and windows
        for (int i = failures.size() - 1; i > -1; i--) {
            IWindow window = failures.get(i);
            if (!windows.remove(window)) {
                failures.remove(window);
            }
        }
    }

    public void start() {
        for(ISensor sensor : this.sensors) {
            sensor.start();
        }
    }
}
